//
//  SoundPlayTool.m
//  HuiYinMaster
//
//  Created by izhifei-Devon on 2017/5/23.
//  Copyright © 2017年 Rowling. All rights reserved.
//

#import "SoundPlayTool.h"
#import "SeverManager.h"

static SoundPlayTool *_instance = nil;

@implementation SoundPlayTool


+ (instancetype)shareSoundPlay{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc]init];

    });
    return _instance;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
       
    });
    return _instance;
}

-(id) copyWithZone:(NSZone *)zone{
    return _instance;
}

-(AVPlayer *)player
{// AVPlayerItem是一个包装音乐资源的类，初始化时可以传入一个音乐的url
    if (_avPlayer == nil){
        AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:@""]];
        _avPlayer = [[AVPlayer alloc]initWithPlayerItem:item];
    }
    return _avPlayer;
}
-(NSMutableArray *)voiceDataArray
{
    if (_voiceDataArray == nil){
        _voiceDataArray = [[NSMutableArray alloc]init];
    }
    return _voiceDataArray;
}
-(void)reloadUI{
    self.playProgress = 0;
    self.loadProgress = 0;
//    self.loadTimeProgress.progress = 0;
}
-(void)playWithUrl:(VoiceListModel *)model{
     AVPlayerItem * item = [[AVPlayerItem alloc]initWithURL:[NSURL URLWithString:@""]];
    if ([[model.mediaUrl substringToIndex:4] isEqualToString:@"http"]){
       item = [[AVPlayerItem alloc]initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",model.mediaUrl]]];
    }else{
       item = [[AVPlayerItem alloc]initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",port,model.mediaUrl]]];
    }
    
    //替换当前音乐资源
    [self.player replaceCurrentItemWithPlayerItem:item];
    //这里应该传参数
    [self reloadUI];
    
    //监听音乐播放完成通知
    [self addNSNotificationForPlayMusicFinish];
    //监听播放器状态
    [self addPlayStatus];
    //监听缓冲进度
    [self addPlayLoadTime];
    
    //监听播放进度
    [self addMusicProgressWithItem:item];
    
    //开始播放
    [self.player play];
   
    //记录当前播放音乐索引
    self.currentId = model.playID;
    
    self.currentModel = model;
}

-(void)play{
    [self playWithUrl:self.voiceDataArray[self.currentId]];
}

-(void)goOnPlay {
    [self.avPlayer play];
}

-(void)pause{
    [self.avPlayer pause];
    [self removePlayStatus];
    [self removePlayLoadTime];
    self.currentModel = nil;
}
#pragma mark - NSNotification

-(void)addNSNotificationForPlayMusicFinish
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    //给AVPlayerItem添加播放完成通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.avPlayer.currentItem];
}
-(void)playFinished:(NSNotification*)notification
{
    //播放下一首
    NSLog(@"播放下一首");
    [self nextVoiceButtonClick];
}
//下一首
-(void)nextVoiceButtonClick{
    if (self.currentId + 1 > self.voiceDataArray.count - 1){
        self.currentId = 0;
    }else{
        self.currentId += 1;
    }
    [self removePlayStatus];
    [self removePlayLoadTime];
    VoiceListModel *model = self.voiceDataArray[self.currentId];
    [self playWithUrl:model];
    
    //    [self.BaseTableView reloadData];
}
//上一首
-(void)upVoiceButtonClick{
    if(self.currentId - 1 < 0){
        self.currentId = (int)(self.voiceDataArray.count) - 1;
    }else{
        self.currentId -= 1;
    }
    [self removePlayStatus];
    [self removePlayLoadTime];
    VoiceListModel *model = self.voiceDataArray[self.currentId];
    [self playWithUrl:model];
    //    [self.BaseTableView reloadData];
}

//移除监听播放器状态
-(void)removePlayStatus
{
    if (self.currentModel == nil) {return;}
    
    [self.player.currentItem removeObserver:self forKeyPath:@"status"];
}

//移除监听音乐缓冲状态
-(void)removePlayLoadTime
{
    if (self.currentModel == nil) {return;}
    [self.player.currentItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
}

#pragma mark - 监听音乐各种状态
//通过KVO监听播放器状态
-(void)addPlayStatus
{
    
    [self.player.currentItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    
}
//KVO监听音乐缓冲状态
-(void)addPlayLoadTime
{
    [self.player.currentItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
    
}
//监听音乐播放的进度
-(void)addMusicProgressWithItem:(AVPlayerItem *)item
{
    //移除监听音乐播放进度
    [self removeTimeObserver];
    __weak typeof(self) weakSelf = self;
    self.timeObserver =  [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        //当前播放的时间
        float current = CMTimeGetSeconds(time);
        //总时间
        float total = CMTimeGetSeconds(item.duration);
        if (current) {
            float progress = current / total;
            //更新播放进度条
            weakSelf.playProgress = progress;
            weakSelf.currentTime = [weakSelf timeFormatted:current];
            weakSelf.totalTime = [weakSelf timeFormatted:total];
        }
    }];
    
}
//转换成时分秒
- (NSString *)timeFormatted:(int)totalSeconds
{
    int seconds = totalSeconds % 60;
    int minutes = (totalSeconds / 60) % 60;
    
    return [NSString stringWithFormat:@"%02d:%02d",minutes, seconds];
}

//移除监听音乐播放进度
-(void)removeTimeObserver
{
    if (self.timeObserver) {
        [self.player removeTimeObserver:self.timeObserver];
        self.timeObserver = nil;
    }
}
//观察者回调
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context

{
    if ([keyPath isEqualToString:@"status"]) {
        switch (self.player.status) {
            case AVPlayerStatusUnknown:
            {
                NSLog(@"未知转态");
            }
                break;
            case AVPlayerStatusReadyToPlay:
            {
                NSLog(@"准备播放");
            }
                break;
            case AVPlayerStatusFailed:
            {
                NSLog(@"加载失败");
            }
                break;
                
            default:
                break;
        }
        
    }
    
    if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
        
        NSArray * timeRanges = self.player.currentItem.loadedTimeRanges;
        //本次缓冲的时间范围
        CMTimeRange timeRange = [timeRanges.firstObject CMTimeRangeValue];
        //缓冲总长度
        NSTimeInterval totalLoadTime = CMTimeGetSeconds(timeRange.start) + CMTimeGetSeconds(timeRange.duration);
        //音乐的总时间
        NSTimeInterval duration = CMTimeGetSeconds(self.player.currentItem.duration);
        //计算缓冲百分比例
        NSTimeInterval scale = totalLoadTime/duration;
        //更新缓冲进度条
//        self.loadTimeProgress.progress = scale;
        self.loadProgress = scale;
    }
}



@end
